import * as vscode from 'vscode';
import { MemFS } from './memfs';

// vscode 插件入口函数
export function activate(context: vscode.ExtensionContext) {

	const memFs = new MemFS();
	context.subscriptions.push(memFs);
	let config = vscode.workspace.getConfiguration("WebPlayground");
	memFs.seed(config.zipUrl);

	// 监听编辑器内容变化
	// 曲线救国，更新配置，并在外围根据配置更新来判断编辑器内容更新
	vscode.workspace.onDidCreateFiles(e => {
		e.files.forEach(item => {
			if (item.path.indexOf(".vscode") >= 0 || item.path.indexOf("settings.json") >= 0) {
				return;
			}
		});
		changeConfig(e);
	});
	vscode.workspace.onDidDeleteFiles(e => {
		e.files.forEach(item => {
			if (item.path.indexOf(".vscode") >= 0 || item.path.indexOf("settings.json") >= 0) {
				return;
			}
		});
		changeConfig(e);
	});
	vscode.workspace.onDidRenameFiles(e => {
		changeConfig(e);
	});
	vscode.workspace.onDidSaveTextDocument(e => {
		if (e.uri.path.indexOf(".vscode") >= 0 || e.uri.path.indexOf("settings.json") >= 0) {
			return;
		}
		changeConfig(e);
	});
	function changeConfig(e) {
		config.update("codeChange", String(new Date().getTime()), true);
	}

	// 获取压缩包
	const commandGenerateZip = 'webPlayground.generateZip';
	const commandGenerateZipHandler = async () => {
		let data = await memFs.generateZip();
		return data;
	};
	context.subscriptions.push(vscode.commands.registerCommand(commandGenerateZip, commandGenerateZipHandler));

	// 加载压缩包
	const commandReloadZip = 'webPlayground.reloadZip';
	const commandReloadZipHandler = async (zipUrl) => {
		if (!zipUrl) {
			// 不传参数，通过判断是否抛异常来判断这条命令是否注册
			return true;
		}
		let success = await memFs.reloadZip(zipUrl);
		return success;
	};
	context.subscriptions.push(vscode.commands.registerCommand(commandReloadZip, commandReloadZipHandler));

}
